/**
 * @author:cavion(曹仁道)
 * @email:caorendao187@163.com
 * 2016年8月29日 
 */
package org.rk.core.generate;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.io.FileUtils;
import org.rk.core.common.util.RKAppConfig;
import org.rk.core.common.util.RkObjectUtil;
import org.rk.core.common.util.RkStrUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.jdbc.support.rowset.SqlRowSetMetaData;


/**
 * @author:cavion 
 * @描述： 
 * 2016年8月29日 下午1:07:19
 */
public class GenUtil {
	private String tCatalog;
	private String tRemark;
	private List<String> colnames; // 列名数组
	private List<String> colTypes; // 列名类型数组
	private List<Integer> colSizes; // 列名大小数组
	private List<Boolean> colNull;//是否为空
	private List<String> colDefValue;//默认值
	private List<String> colRemark;//注释
	private boolean f_util; // 是否需要导入包java.util.*
	private boolean f_sql; // 是否需要导入包java.sql.*
	private List<GenBean> beanInfoList;
	private DataSource dataSource=RKAppConfig.getBean(DataSource.class,"dataSource");
	private JdbcTemplate jdbcTemplate;

	public GenUtil(List<GenBean> beanInfoList) {
		this.beanInfoList=beanInfoList;
	}
	public GenUtil(String packagePath, String tableName,String projectPath) {
		GenBean genBean=new GenBean();
		genBean.setPackagePath(packagePath);
		genBean.setProjectPath(projectPath);
		genBean.setTableName(tableName);
		this.beanInfoList.add(genBean);
	}
	public GenUtil(String packagePath, String tableName,String projectPath,String baseBeanName) {
		GenBean genBean=new GenBean();
		genBean.setPackagePath(packagePath);
		genBean.setProjectPath(projectPath);
		genBean.setTableName(tableName);
		genBean.setBaseBeanName(baseBeanName);
		this.beanInfoList.add(genBean);
	}
	public GenUtil(String packagePath, String tableName,String projectPath,boolean isGenDao,boolean isGeanService) {
		GenBean genBean=new GenBean();
		genBean.setPackagePath(packagePath);
		genBean.setProjectPath(projectPath);
		genBean.setTableName(tableName);
		genBean.setGeanService(isGeanService);
		genBean.setGenDao(isGenDao);
		this.beanInfoList.add(genBean);
	}

	public void genEntity(){
		if(RkObjectUtil.isEmpty(jdbcTemplate)){
			jdbcTemplate=new JdbcTemplate(dataSource);
		}
		for (GenBean genBean : beanInfoList) {
			colnames=new ArrayList<String>();
			colTypes=new ArrayList<String>();
			colSizes=new ArrayList<Integer>();
			colNull=new ArrayList<Boolean>();
			colDefValue=new ArrayList<String>();
			colRemark=new ArrayList<String>();
			f_util = true;
			f_sql = false;
			genSingleEntity(genBean.getPackagePath(),genBean.getTableName(),genBean.getProjectPath());
		}
	}
	public void genSingleEntity(String packagePath,String tableName,String projectPath){
		genSingleEntityV2(packagePath, tableName, projectPath,true,true,true,"BaseBean");
	}
	public void genSingleEntity(String packagePath,String tableName,String projectPath,boolean isGenDao,boolean isGeanService,boolean isGenController,String baseBeanName){
		String strsql = "select * from " + tableName;
		SqlRowSet srs=jdbcTemplate.queryForRowSet(strsql);
		SqlRowSetMetaData  srsmd=srs.getMetaData();
		int size = srsmd.getColumnCount();// 共有多少列
		for (int i = 0; i < size; i++) {
			String cName=srsmd.getColumnName(i + 1);
			String cType=srsmd.getColumnTypeName(i + 1);
			if(RkStrUtil.isEmpty(cName)||RkStrUtil.isEmpty(cType)||isContinue(cName,baseBeanName)){
				continue;
			}
			
			tCatalog=srsmd.getCatalogName(i+1);
			colnames.add(cName);
			colTypes.add(cType);
			if (cType.equalsIgnoreCase("datetime")||cType.equalsIgnoreCase("Timestamp")) {
				//f_util = true;
				f_sql = true;
			}
			if (cType.equalsIgnoreCase("image") || cType.equalsIgnoreCase("text")|| cType.equalsIgnoreCase("longtext")) {
				f_sql = true;
			}
			 colSizes.add(srsmd.getColumnDisplaySize(i + 1));
			 //colNull.add(srsmd.isNullable(i+1)==0?false:true);
			 colNull.add(false);
		}
		
		try {
			//实体
			String content = this.parse(packagePath,tableName,baseBeanName);
			//dao
			String daoContent="";
			String IdaoContent="";
			if(isGenDao){
				daoContent = this.parseDao(packagePath,tableName);
				IdaoContent=this.parseInterfaceDao(packagePath, tableName);
			}
			//service
			String serviceContent="";
			String IserviceContent="";
			if(isGeanService){
				serviceContent = this.parseService(packagePath,tableName);
				IserviceContent=this.parseInterfaceService(packagePath, tableName);
			}
			//controller
			String webController="";
			String adminController="";
			if(isGenController){
				webController=this.parseWebController(packagePath, tableName);
				adminController=this.parseAdminController(packagePath, tableName);
			}
			
			String path = projectPath + "/src/main/java/" + packagePath.replaceAll("\\.", "/");
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			String beanName=initcap(tableName);
			String daoClassName=beanName+"Dao";
			String IdaoClassName="I"+beanName+"Dao";
			
			String serviceClassName=beanName+"Service";
			String IserviceClassName="I"+beanName+"Service";
			
			String webControllerClassName=beanName+"Web";
			String adminControllerClassName=beanName+"Admin";
			
			String beanPath = path + "/" + beanName + ".java";
			System.out.println("beanPath:" + beanPath);
			FileUtils.writeStringToFile(new File(beanPath), content,"UTF-8");
			
			if(isGenDao){
				String daoPath = path + "/dao/" + daoClassName + ".java";
				String IdaoPath = path + "/dao/" + IdaoClassName + ".java";
				System.out.println("IdaoPath:"+IdaoPath+";daoPath:" + daoPath);
				FileUtils.writeStringToFile(new File(daoPath), daoContent,"UTF-8");
				FileUtils.writeStringToFile(new File(IdaoPath), IdaoContent,"UTF-8");
			}
			if(isGeanService){
				String servicePath = path + "/service/" + serviceClassName + ".java";
				String IservicePath = path + "/service/" + IserviceClassName + ".java";
				System.out.println("IservicePath:" + IservicePath+";servicePath:" + servicePath);
				FileUtils.writeStringToFile(new File(servicePath), serviceContent,"UTF-8");
				FileUtils.writeStringToFile(new File(IservicePath), IserviceContent,"UTF-8");
			}
			//controller
			if(isGenController){
				String webControllerPath = path + "/controller/" + webControllerClassName + ".java";
				String adminControllerPath = path + "/controller/" + adminControllerClassName + ".java";
				System.out.println("webControllerClassName:" + webControllerClassName+";\r\n adminControllerClassName:" + adminControllerClassName);
				FileUtils.writeStringToFile(new File(webControllerPath), webController,"UTF-8");
				FileUtils.writeStringToFile(new File(adminControllerPath), adminController,"UTF-8");
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void genSingleEntityV2(String packagePath,String tableName,String projectPath,boolean isGenDao,boolean isGeanService,boolean isGenController,String baseBeanName){
		//String strsql = "select * from " + tableName;
		try {
			Connection con=dataSource.getConnection();
			DatabaseMetaData dmd=con.getMetaData();
			ResultSet rsTable=dmd.getTables(null, null, tableName, new String[]{"TABLE"});
			while(rsTable.next()){
				tCatalog=rsTable.getString("TABLE_CAT");//表所在表空间或数据库名
				tRemark=rsTable.getString("REMARKS");//表注释
			}
			ResultSet rsCol=dmd.getColumns(null, null, tableName, null);
			while(rsCol.next()){
				String cName=rsCol.getString("COLUMN_NAME");//列名
				int cDType=rsCol.getInt("DATA_TYPE");//列数据类型  java.sql.Types
				int cSize=rsCol.getInt("COLUMN_SIZE");//列长度
				int cNull=rsCol.getInt("NULLABLE");//是否允许为空
				String cRemark=rsCol.getString("REMARKS");//列注释
				String cDefValue=rsCol.getString("COLUMN_DEF");//默认值
				if(RkStrUtil.isEmpty(cName)||isContinue(cName,baseBeanName)){
					continue;
				}
				String cType=colDataTypeToString(cDType);
				if (cType.equalsIgnoreCase("datetime")||cType.equalsIgnoreCase("Timestamp")||cType.equalsIgnoreCase("image") || cType.equalsIgnoreCase("text")|| cType.equalsIgnoreCase("longtext")) {
					f_sql = true;
				}
				colnames.add(cName);
				colTypes.add(cType);
				colSizes.add(cSize);
				colNull.add(cNull==1?true:false);
				if("null".equals(cDefValue)){
					cDefValue="";
				}
				colDefValue.add(cDefValue);
				colRemark.add(cRemark);
			}
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			String content = this.parse(packagePath,tableName,baseBeanName);
			
			String daoContent="";
			String IdaoContent="";
			if(isGenDao){
				daoContent = this.parseDao(packagePath,tableName);
				IdaoContent=this.parseInterfaceDao(packagePath, tableName);
			}
			
			String serviceContent="";
			String IserviceContent="";
			if(isGeanService){
				serviceContent = this.parseService(packagePath,tableName);
				IserviceContent=this.parseInterfaceService(packagePath, tableName);
			}
			String webController="";
			String adminController="";
			if(isGenController){
				webController=this.parseWebController(packagePath, tableName);
				adminController=this.parseAdminController(packagePath, tableName);
			}
			
			String path = projectPath + "/src/main/java/" + packagePath.replaceAll("\\.", "/");
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			String beanName=initcap(tableName);
			
			String daoClassName=beanName+"Dao";
			String IdaoClassName="I"+beanName+"Dao";
			
			String serviceClassName=beanName+"Service";
			String IserviceClassName="I"+beanName+"Service";
			
			String webControllerClassName=beanName+"Web";
			String adminControllerClassName=beanName+"Admin";
			
			String beanPath = path + "/" + beanName + ".java";
			System.out.println("beanPath:" + beanPath);
			FileUtils.writeStringToFile(new File(beanPath), content,"UTF-8");
			if(isGenDao){
				String daoPath = path + "/dao/" + daoClassName + ".java";
				String IdaoPath = path + "/dao/" + IdaoClassName + ".java";
				System.out.println("IdaoPath:"+IdaoPath+";\r\n daoPath:" + daoPath);
				FileUtils.writeStringToFile(new File(daoPath), daoContent,"UTF-8");
				FileUtils.writeStringToFile(new File(IdaoPath), IdaoContent,"UTF-8");
			}
			if(isGeanService){
				String servicePath = path + "/service/" + serviceClassName + ".java";
				String IservicePath = path + "/service/" + IserviceClassName + ".java";
				System.out.println("IservicePath:" + IservicePath+";\r\n servicePath:" + servicePath);
				FileUtils.writeStringToFile(new File(servicePath), serviceContent,"UTF-8");
				FileUtils.writeStringToFile(new File(IservicePath), IserviceContent,"UTF-8");
			}
			if(isGenController){
				String webControllerPath = path + "/controller/" + webControllerClassName + ".java";
				String adminControllerPath = path + "/controller/" + adminControllerClassName + ".java";
				System.out.println("webControllerClassName:" + webControllerClassName+";\r\n adminControllerClassName:" + adminControllerClassName);
				FileUtils.writeStringToFile(new File(webControllerPath), webController,"UTF-8");
				FileUtils.writeStringToFile(new File(adminControllerPath), adminController,"UTF-8");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private String colDataTypeToString(int cDType){
		String cType="";
		switch(cDType){
			case Types.VARCHAR:
				cType="VARCHAR";
				break;
			case Types.BIT:
				cType="BIT";
				break;
			case Types.BLOB:
				cType="BLOB";
				break;
			case Types.BOOLEAN:
				cType="BOOLEAN";
				break;
			case Types.CHAR:
				cType="CHAR";
				break;
			case Types.CLOB:
				cType="CLOB";
				break;
			case Types.DATE:
				cType="DATE";
				break;
			case Types.DECIMAL:
				cType="DECIMAL";
				break;
			case Types.DOUBLE:
				cType="DOUBLE";
				break;
			case Types.INTEGER:
				cType="INTEGER";
				break;
			case Types.NUMERIC:
				cType="NUMERIC";
				break;
			case Types.TIMESTAMP:
				cType="TIMESTAMP";
				break;
			case Types.BIGINT:
				cType="BIGINT";
				break;
			case Types.NVARCHAR:
				cType="NVARCHAR";
				break;
			case Types.LONGNVARCHAR:
				cType="LONGNVARCHAR";
				break;
			case Types.LONGVARCHAR:
				cType="LONGVARCHAR";
				break;
		}
		return cType;
	}
	/**
	 * 解析处理(生成实体类主体代码)
	 */
	private String parse(String packagePath,String tableName,String baseBeanName) {
		if(RkStrUtil.isEmpty(baseBeanName)){
			baseBeanName="BaseBean";
		}
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packagePath + ";\r\n\r\n");
		sb.append("import javax.validation.constraints.NotNull;\r\n");
		sb.append("import org.rk.core.common.anno.FieldMeta;\r\n");
		sb.append("import org.rk.core.common.anno.TableMeta;\r\n");
		sb.append("import org.rk.core.common.bean."+baseBeanName+";\r\n");
		//sb.append("import javax.persistence.GeneratedValue;\r\n");
		//sb.append("import javax.persistence.GenerationType;\r\n");
		//sb.append("import javax.persistence.Id;\r\n");
		//sb.append("import java.io.Serializable;\r\n");
		if (f_util) {
			sb.append("import java.util.*;\r\n\r\n\r\n");
		}
		if (f_sql) {
			sb.append("import java.sql.*;\r\n\r\n\r\n");
		}
		//注解
		sb.append("@TableMeta(name = \""+tableName+"\", catalog = \""+tCatalog+"\",desc=\""+tRemark+"\")\r\n");
		//类继承基础bean
		sb.append("public class " + initcap(tableName) + " extends "+baseBeanName+"{\r\n\r\n");
		sb.append("\tprivate static final long serialVersionUID = 1L;\r\n");//
		processAllAttrs(sb);
		sb.append("\r\n");
		processAllMethod(sb);
		sb.append("}\r\n");
		return sb.toString();

	}
	/**
	 * @方法描述：生成DAO类
	 * @author Cavion(曹仁道)
	 * @param packagePath
	 * @param tableName
	 * @return
	 * 2016年11月12日 下午2:43:17
	 */
	private String parseDao(String packagePath,String tableName){
		//生成类名
		String beanName=initcap(tableName);
		String className=beanName+"Dao";
		String IclassName="I"+beanName+"Dao";
		
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packagePath + ".dao;\r\n\r\n");
		//引包
		sb.append("import javax.annotation.Resource;\r\n");
		sb.append("import org.springframework.jdbc.core.JdbcTemplate;\r\n");
		sb.append("import org.springframework.stereotype.Repository;\r\n");
		sb.append("import "+packagePath+"."+beanName+";\r\n");
		sb.append("import org.rk.core.pub.base.dao.DBDao;\r\n\r\n\r\n");
		//注解
		sb.append("@Repository(\""+className+"\")\r\n");
		//类继承DBDao
		sb.append("public class "+className+" extends DBDao<"+beanName+"> implements "+IclassName+"{\r\n\r\n");
		sb.append("\t@Resource\r\n");
		sb.append("\tpublic void setJdbcTemplate(JdbcTemplate jdbcTemplate) {\r\n");
		sb.append("\t\tsuper.setJdbcTemplate(jdbcTemplate);\r\n");
		sb.append("\t}\r\n");
		//生成根据主键删除方法
		sb.append("\t@Override\r\n");
		sb.append("\tpublic boolean deleteById(Long id){\r\n");
		sb.append("\t\t"+beanName+" model=new "+beanName+"();\r\n");
		sb.append("\t\tmodel.setId(id);\r\n");
		sb.append("\t\treturn super.deleteModel(model);\r\n");
		sb.append("\t}\r\n");
		
		sb.append("}\r\n");
		
		return sb.toString();
	}
	/**
	 * @方法描述：生成dao接口
	 * @author:Cavion(曹仁道)
	 * @param packagePath
	 * @param tableName
	 * @return
	 * 2016年12月10日
	 */
	private String parseInterfaceDao(String packagePath,String tableName){
		//生成类名
		String beanName=initcap(tableName);
		String className="I"+beanName+"Dao";
		
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packagePath + ".dao;\r\n\r\n");
		//引包
		sb.append("import org.rk.core.pub.base.dao.IDBDao;\r\n");
		sb.append("import "+packagePath+"."+beanName+";\r\n");
		//接口继承IDBDao
		sb.append("public interface "+className+" extends IDBDao<"+beanName+"> {\r\n\r\n");
		//生成根据主键删除方法
		sb.append("\tpublic boolean deleteById(Long id);\r\n");
		
		sb.append("}\r\n");
		
		return sb.toString();
	}
	/**
	 * 
	 * @方法描述：生成service类
	 * @author Cavion(曹仁道)
	 * @param packagePath
	 * @param tableName
	 * @return
	 * 2016年11月12日 下午2:51:03
	 */
	private String parseService(String packagePath,String tableName){
		//生成类名
		String beanName=initcap(tableName);
		String IdaoClassName="I"+beanName+"Dao";
		String daoClassName=beanName+"Dao";
		String className=beanName+"Service";
		String IclassName="I"+beanName+"Service";
		
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packagePath + ".service;\r\n\r\n");
		//引包
		sb.append("import javax.annotation.Resource;\r\n");
		sb.append("import org.springframework.stereotype.Service;\r\n");
		sb.append("import org.springframework.transaction.annotation.Transactional;\r\n");
		sb.append("import "+packagePath+"."+beanName+";\r\n");
		sb.append("import "+packagePath+".dao."+IdaoClassName+";\r\n");
		sb.append("import org.rk.core.pub.base.service.ModelService;\r\n\r\n\r\n");
		//注解
		sb.append("@Service(\""+className+"\")\r\n");
		//类继承DBDao
		sb.append("public class "+className+" extends ModelService<"+beanName+"> implements "+IclassName+"{\r\n\r\n");
		sb.append("\tprivate "+IdaoClassName+" modelDao;\r\n");
		sb.append("\t@Resource(name=\""+daoClassName+"\")\r\n");
		sb.append("\tpublic void set"+daoClassName+"("+IdaoClassName+" modelDao) {\r\n");
		sb.append("\t\tsuper.setDbDao(modelDao);\r\n");
		sb.append("\t\tthis.modelDao=modelDao;\r\n");
		sb.append("\t}\r\n");
		//生成根据主键删除方法
		sb.append("\t@Override\r\n");
		sb.append("\t@Transactional\r\n");
		sb.append("\tpublic boolean deleteById(Long id){\r\n");
		sb.append("\t\treturn modelDao.deleteById(id);\r\n");
		sb.append("\t}\r\n");
		
		sb.append("}\r\n");
		
		return sb.toString();
	}
	/**
	 * @方法描述：生成service接口
	 * @author:Cavion(曹仁道)
	 * @param packagePath
	 * @param tableName
	 * @return
	 * 2016年12月10日
	 */
	private String parseInterfaceService(String packagePath,String tableName){
		//生成类名
		String beanName=initcap(tableName);
		String className="I"+beanName+"Service";
		
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packagePath + ".service;\r\n\r\n");
		//引包
		sb.append("import "+packagePath+"."+beanName+";\r\n");
		sb.append("import org.rk.core.pub.base.service.IModelService;\r\n\r\n\r\n");
		//接口继承IModelService
		sb.append("public interface "+className+" extends IModelService<"+beanName+"> {\r\n\r\n");
		//生成根据主键删除方法
		sb.append("\tpublic boolean deleteById(Long id);\r\n");
		
		sb.append("}\r\n");
		
		return sb.toString();
	}
	/**
	 * @方法描述：生成web Controller
	 * @param packagePath
	 * @param tableName
	 * @return
	 */
	private String parseWebController(String packagePath,String tableName){
		//生成类名
		String beanName=initcap(tableName);
		String className=beanName+"Web";
		String serviceClassName=beanName+"Service";
		String iserviceClassName="I"+beanName+"Service";
		String varBeanStr=this.getCamelStr(tableName);
		String varServiceStr=varBeanStr+"Service";
		
		StringBuffer sb=new StringBuffer();
		sb.append("package " + packagePath + ".controller;\r\n\r\n");
		//引包
		sb.append("import java.util.HashMap;\r\n");
		sb.append("import java.util.List;\r\n");
		sb.append("import java.util.Map;\r\n\r\n");
		sb.append("import javax.annotation.Resource;\r\n\r\n");
		sb.append("import org.apache.shiro.authz.annotation.RequiresPermissions;\r\n");
		sb.append("import org.springframework.stereotype.Controller;\r\n");
		sb.append("import org.springframework.web.bind.annotation.RequestMapping;\r\n");
		sb.append("import org.springframework.web.bind.annotation.RequestMethod;\r\n");
		sb.append("import org.springframework.web.bind.annotation.ResponseBody;\r\n\r\n");
		
		sb.append("import org.rk.core.pub.base.controller.BaseController;\r\n");
		sb.append("import org.rk.core.common.bean.PageData;\r\n");
		sb.append("import org.rk.core.common.util.RkObjectUtil;\r\n");
		sb.append("import "+packagePath+"."+beanName+";\r\n");
		sb.append("import "+packagePath+".service."+iserviceClassName+";\r\n\r\n\r\n");
		
		//构建类
		sb.append("@Controller\r\n");
		String[] urlPaths=packagePath.split(".");
		String urlPath="";
		for (int i=0;i<urlPaths.length;i++) {
			String str=urlPaths[i];
			if(i==1){
				urlPath+="/web"+str;
			}else if(i==(urlPaths.length-1)){
				urlPath+="/"+str+"/";
			}else{
				urlPath+="/"+str;
			}
			
		}
		sb.append("@RequestMapping(\""+urlPath+"\")\r\n");
		sb.append("public class "+className+" extends BaseController<"+beanName+"> {\r\n");
		sb.append("\t@Resource(name = \""+serviceClassName+"\")\r\n");
		sb.append("\tprivate "+iserviceClassName+" "+varServiceStr+";\r\n");
		//查询分页
		sb.append("\t@RequestMapping(value = \"queryPage\", method = RequestMethod.POST)\r\n");
		sb.append("\tpublic @ResponseBody Object queryPage(int start, int length, int draw) {\r\n");
		sb.append("\t\tMap<String, Object> params = new HashMap<String, Object>();\r\n");
		sb.append("\t\tPageData page = new PageData();\r\n");
		sb.append("\t\tpage.setStart(start);\r\n");
		sb.append("\t\tpage.setLength(length);\r\n");
		sb.append("\t\tpage.setDraw(draw);\r\n");
		sb.append("\t\tpage = "+varServiceStr+".selectModelListPage(params, page);\r\n");
		sb.append("\t\treturn page;\r\n");
		sb.append("\t\t}\r\n\r\n");
		//查询集合
		sb.append("\t@RequestMapping(value = \"queryList\", method = RequestMethod.POST)\r\n");
		sb.append("\tpublic @ResponseBody Object queryList() {\r\n");
		sb.append("\t\tMap<String, Object> params = new HashMap<String, Object>();\r\n");
		sb.append("\t\tList<"+beanName+"> resultList = "+varServiceStr+".selectModelList(params);\r\n");
		sb.append("\t\tif (RkObjectUtil.isEmpty(resultList)||resultList.size()<1) {\r\n");
		sb.append("\t\t\treturn ajaxError(\"没有找到数据\");\r\n");
		sb.append("\t\t}\r\n");
		sb.append("\t\treturn resultList;\r\n");
		sb.append("\t}\r\n\r\n");
		//根据id查询
		sb.append("\t@RequestMapping(value = \"query\", method = RequestMethod.POST)\r\n");
		sb.append("\tpublic @ResponseBody Object query(Long id) {\r\n");
		sb.append("\t\t"+beanName+" "+varBeanStr+" = "+varServiceStr+".selectModel(id);\r\n");
		sb.append("\t\tif (RkObjectUtil.isEmpty("+varBeanStr+")) {\r\n");
		sb.append("\t\t\treturn ajaxError(\"没有找到数据\");\r\n");
		sb.append("\t\t}\r\n");
		sb.append("\t\treturn "+varBeanStr+";\r\n");
		sb.append("\t}\r\n");
		//getService方法
		sb.append("\tpublic "+iserviceClassName+" get"+serviceClassName+"() {\r\n");
		sb.append("\t\treturn "+varServiceStr+";\r\n");
		sb.append("\t}\r\n\r\n");
		
		sb.append("}\r\n");
		return sb.toString();
	}
	/**
	 * @方法描述：生成admin Controller
	 * @param packagePath
	 * @param tableName
	 * @return
	 */
	private String parseAdminController(String packagePath, String tableName) {
		// 生成类名
		String beanName = initcap(tableName);
		String webClassName = beanName + "Web";
		String className = beanName + "Admin";
		String serviceClassName = beanName + "Service";
		//String iserviceClassName = "I" + beanName + "Service";
		String varBeanStr = this.getCamelStr(tableName);
		//String varServiceStr = varBeanStr + "Service";

		StringBuffer sb = new StringBuffer();
		sb.append("package " + packagePath + ".controller;\r\n\r\n");
		// 引包
		//sb.append("import java.util.HashMap;\r\n");
		sb.append("import java.util.List;\r\n");
		//sb.append("import java.util.Map;\r\n\r\n");
		sb.append("import org.apache.shiro.authz.annotation.RequiresPermissions;\r\n");
		sb.append("import org.springframework.stereotype.Controller;\r\n");
		sb.append("import org.springframework.web.bind.annotation.RequestMapping;\r\n");
		sb.append("import org.springframework.web.bind.annotation.RequestMethod;\r\n");
		sb.append("import org.springframework.web.bind.annotation.RequestParam;\r\n");
		sb.append("import org.springframework.web.bind.annotation.ResponseBody;\r\n\r\n");

		
		sb.append("import org.rk.core.auth.util.SecurityUtil;\r\n");
		sb.append("import org.rk.core.common.util.RkObjectUtil;\r\n");
		sb.append("import " + packagePath + "." + beanName + ";\r\n");
		//sb.append("import " + packagePath + "." + iserviceClassName + ";\r\n\r\n\r\n");

		// 构建类
		sb.append("@Controller\r\n");
		String[] urlPaths = packagePath.split(".");
		String urlPath = "";
		for (int i = 0; i < urlPaths.length; i++) {
			String str = urlPaths[i];
			if (i == 1) {
				urlPath += "/admin" + str;
			} else if (i == (urlPaths.length - 1)) {
				urlPath += "/" + str + "/";
			} else {
				urlPath += "/" + str;
			}

		}
		sb.append("@RequestMapping(\"" + urlPath + "\")\r\n");
		sb.append("public class "+className+" extends "+webClassName+" {\r\n");
		// 保存
		sb.append("\t@RequiresPermissions(value=\""+varBeanStr+":save\")\r\n");
		sb.append("\t@RequestMapping(value = \"save\", method = RequestMethod.POST)\r\n");
		sb.append("\tpublic @ResponseBody Object save("+beanName+" "+varBeanStr+") {\r\n");
		sb.append("\t\tif(RkObjectUtil.isEmpty("+varBeanStr+".getId())){\r\n");
		sb.append("\t\t\t"+varBeanStr+".setCreator(SecurityUtil.getUserName());\r\n");
		sb.append("\t\t\tget"+serviceClassName+"().insertModel("+varBeanStr+");\r\n");
		sb.append("\t\t}else{\r\n");
		sb.append("\t\t\t"+varBeanStr+".setUpdator(SecurityUtil.getUserName());\r\n");
		sb.append("\t\t\tget"+serviceClassName+"().updateModel("+varBeanStr+");\r\n");
		sb.append("\t\t}\r\n");
		sb.append("\t\treturn ajaxSucc(\"保存成功\");\r\n");
		sb.append("\t}\r\n\r\n");
		// 删除
		sb.append("\t@RequiresPermissions(value=\""+varBeanStr+":delete\")\r\n");
		sb.append("\t@RequestMapping(value = \"delete\", method = RequestMethod.POST)\r\n");
		sb.append("\tpublic @ResponseBody Object delete(@RequestParam(\"idArr[]\") List<Long> idArr) {\r\n");
		sb.append("\t\tfor (Long id : idArr) {\r\n");
		sb.append("\t\t\tget"+serviceClassName+"().deleteById(id);\r\n");
		sb.append("\t\t}\r\n");
		sb.append("\t\treturn ajaxSucc(\"删除成功\");\r\n");
		sb.append("\t}\r\n");

		sb.append("}\r\n");
		return sb.toString();
	}
	/**
	 * 生成所有的方法
	 * 
	 * @param sb
	 */
	private void processAllMethod(StringBuffer sb) {
		for (int i = 0; i < colnames.size(); i++) {
			sb.append("\tpublic void set" + initcap(this.getCamelStr(colnames.get(i))) + "(" + sqlType2JavaType(colTypes.get(i)) + " " + this.getCamelStr(colnames.get(i)) + "){\r\n");
			sb.append("\t\tthis." + this.getCamelStr(colnames.get(i)) + "=" + this.getCamelStr(colnames.get(i)) + ";\r\n");
			sb.append("\t}\r\n\r\n");
			/*if(colnames.get(i).equals("id")){
				sb.append("\t@GeneratedValue(strategy=GenerationType.IDENTITY)\r\n");
				sb.append("\t@Id\r\n");
				sb.append("\t@Column(name = \"id\", unique = true, nullable = false, length = 50,updatable=false)\r\n");
			}else{
				sb.append("\t@Column(name = \""+colnames.get(i)+"\", length = "+colSizes.get(i)+")\r\n");
			}*/
			sb.append("\tpublic " + sqlType2JavaType(colTypes.get(i)) + " get" + initcap(this.getCamelStr(colnames.get(i))) + "(){\r\n");
			sb.append("\t\treturn " + this.getCamelStr(colnames.get(i)) + ";\r\n");
			sb.append("\t}\r\n\r\n");
		}
	}
	/**
	 * 
	 * @author:cavion
	 * @描述：是否需要跳过的属性
	 * 2016年10月27日 下午8:45:54
	 * @return
	 */
	private boolean isContinue(String cName,String baseBeanName){
		if(cName.equalsIgnoreCase("id")||cName.equalsIgnoreCase("creator")||cName.equalsIgnoreCase("updator")
				||cName.equalsIgnoreCase("createTime")||cName.equalsIgnoreCase("updateTime")){//这几个在基础bean中
			return true;
		}
		if("TreeBean".equals(baseBeanName)){//如果继承树，再过滤几个
			if(cName.equalsIgnoreCase("fatherCode")||cName.equalsIgnoreCase("code")||cName.equalsIgnoreCase("name")){
				return true;
			}
		}
		return false;
	}
	/**
	 * 解析输出属性
	 * 
	 * @return
	 */
	private void processAllAttrs(StringBuffer sb) {
		for (int i = 0; i < colnames.size(); i++) {
			if(!colNull.get(i)){
				sb.append("\t@NotNull\r\n");
			}
			String defValue=colDefValue.get(i);
			if(!RkStrUtil.hasText(defValue)){
				defValue="";
			}
			sb.append("\t@FieldMeta(name=\""+colnames.get(i)+"\",length="+colSizes.get(i)+",desc=\""+colRemark.get(i)+"\",defaultValue=\""+defValue+"\")\r\n");
			sb.append("\tprivate " + sqlType2JavaType(colTypes.get(i)) + " " + this.getCamelStr(colnames.get(i)) + ";\r\n");
		}
	}

	/**
	 * 把输入字符串的首字母改成大写
	 * 
	 * @param str
	 * @return
	 */
	private String initcap(String str) {
		char[] ch = str.toCharArray();
		if (ch[0] >= 'a' && ch[0] <= 'z') {
			ch[0] = (char) (ch[0] - 32);
		}
		return this.getCamelStr(new String(ch));
	}

	/**
	 * @author:cavion
	 * @描述：例：user_name --> userName
	 * 2016年10月27日 下午8:53:48
	 * @param s
	 * @return
	 */
	private String getCamelStr(String s) {
		while (s.indexOf("_") > 0) {
			int index = s.indexOf("_");
			// System.out.println(s.substring(index+1, index+2).toUpperCase());
			s = s.substring(0, index) + s.substring(index + 1, index + 2).toUpperCase() + s.substring(index + 2);
		}
		return s;
	}

	private String sqlType2JavaType(String sqlType) {
		if(!RkStrUtil.isEmpty(sqlType)){
			sqlType=sqlType.toLowerCase();
		}else{
			return "";
		}
		if (sqlType.equalsIgnoreCase("bit")) {
			return "Boolean";
		} else if (sqlType.equalsIgnoreCase("tinyint")) {
			return "byte";
		} else if (sqlType.equalsIgnoreCase("smallint")) {
			return "short";
		} else if (sqlType.equalsIgnoreCase("int") || sqlType.equalsIgnoreCase("integer")) {
			return "Integer";
		} else if (sqlType.equalsIgnoreCase("bigint")) {
			return "Long";
		} else if (sqlType.equalsIgnoreCase("float")) {
			return "Float";
		} else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
				|| sqlType.equalsIgnoreCase("real")) {
			return "BigDecimal";
		} else if (sqlType.equalsIgnoreCase("money") || sqlType.equalsIgnoreCase("smallmoney")) {
			return "Double";
		} else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
				|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
				|| sqlType.equalsIgnoreCase("longvarchar")|| sqlType.equalsIgnoreCase("longnvarchar")
				||sqlType.equalsIgnoreCase("text")||sqlType.equalsIgnoreCase("longtext")) {
			return "String";
		} else if (sqlType.equalsIgnoreCase("datetime")||sqlType.equalsIgnoreCase("timestamp")) {
			return "Timestamp";
		}else if (sqlType.equalsIgnoreCase("date")) {
			return "Date";
		}else if (sqlType.equalsIgnoreCase("image")) {
			return "byte[]";
		}
		return null;
	}

	public static void main(String[] args) {
		//String packagePath = "rk.core.test.pojo";
		//String tableName = "core_domain";
		//new GenEntityUtil(packagePath, tableName);
	}

}
